<?php

namespace app\admin\controller;

use app\common\model;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Validate;

/**
 * 老师
 *
 * Class Teacher
 * @package app\admin\controller
 */
class Teacher extends Backend
{
    /**
     * @var \app\common\model\Grade
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = [];
    protected $genderData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Teacher');

        $this->genderData =  model\User::$genderList;
        $this->view->assign('genderData', $this->genderData);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {


            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->where($where)->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['gender_text'])->toArray();
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {

                $group_id = $this->request->post('group_id');
                $group_type = $this->request->post('group_type', 1);
                $group_end_time = $this->request->post('group_end_time');

                if ($group_id && $group_type == '2' && !$group_end_time)
                    $this->error('请选择到期时间');

                $params['creator_id'] = $this->auth->id;

                $validate = Validate('Teacher');
                $res = $validate->scene('add')->check($params);
                if (!$res) {
                    $this->error($validate->getError());
                }

                // 启动事务
                Db::startTrans();
                try {
                    $this->model->save($params);

                    $auth = new Auth();
                    $extend['target_id'] = $this->model->id;
                    $extend['target_type'] = model\User::TEACHER;
                    $extend['nickname'] = $params['name'];
                    $extend['gender'] = $params['gender'];
                    if ($group_id) {
                        $extend['group_id'] = $group_id;
                        if ($group_type == 2) {
                            $extend['group_end_time'] = strtotime($group_end_time);
                        } else {
                            $extend['group_end_time'] =  0;
                        }
                    }
                    $auth->register($params['name'], '123456', '', $params['mobile'], $extend);

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage() ? $e->getMessage() : __('添加失败'));
                }

                $this->success();

            }
            $this->error();
        }

        $User_group = model\UserGroup::column('id,name');
        $group[0] = '请选择';
        foreach ($User_group as $key => $value) {
            $group[$key] = $value;
        }
        $this->view->assign('groupList', build_select('group_id', $group, null, ['class' => 'form-control selectpicker']));
        $group_type = ['0' => '请选择', '1' => '长期', '2' => '短期'];
        $this->view->assign('groupTypeList', build_select('group_type', $group_type, null, ['class' => 'form-control selectpicker group_type']));

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $user = model\User::where('target_id', $row['id'])
            ->where('target_type', model\User::TEACHER)
            ->field('id,group_id,group_end_time')
            ->find();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {

                $validate = Validate('Teacher');
                $res = $validate->scene('edit')->check($params);
                if (!$res) {
                    $this->error($validate->getError());
                }

                $group_id = $this->request->post('group_id');
                $group_type = $this->request->post('group_type', 1);
                $group_end_time = $this->request->post('group_end_time');

                if ($group_id && $group_type == 2 && !$group_end_time)
                    $this->error('请选择到期时间');

                // 启动事务
                Db::startTrans();
                try {
                    $row->save($params);

                    if ($user) {

                        if ($group_id) {
                            $user->group_id = $group_id;

                            if ($group_type == 2) {
                                $user->group_end_time = strtotime($group_end_time);
                            } else {
                                $user->group_end_time =  0;
                            }
                        }

                        $user->username = $params['name'];
                        $user->gender   = $params['gender'];
                        $user->mobile   = $params['mobile'];

                        $user->save();
                    }

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage() ? $e->getMessage() : __('保存失败'));
                }

                $this->success();
            }
            $this->error();
        }

        $User_group = model\UserGroup::column('id,name');
        $group[0] = '请选择';
        foreach ($User_group as $key => $value) {
            $group[$key] = $value;
        }

        $this->view->assign('groupList', build_select('group_id', $group, $user['group_id'], ['class' => 'form-control selectpicker']));

        $row['group_type'] = 0;
        $row['group_end_time'] = '';
        if ($user['group_end_time'] === 0) {
            $row['group_type'] = 1;
        } else if ($user['group_end_time'] > 0) {
            $row['group_type'] = 2;
            $row['group_end_time'] = date('Y-m-d H:i:s', $user['group_end_time']);
        }
        $group_type = ['0' => '请选择', '1' => '长期', '2' => '短期'];
        $this->view->assign('groupTypeList', build_select('group_type', $group_type, $row['group_type'], ['class' => 'form-control selectpicker group_type']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $ids = explode(',', $ids);
            $ids = array_unique($ids);

            $count = $this->model->where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }





}
